import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import Breadcrumb from '../components/common/Breadcrumb';
import BackToTop from '../components/common/BackToTop';
import { blogPosts } from '../data/blogPosts';
import './BlogPage.css';

const BlogPage = () => {
  const [posts, setPosts] = useState(blogPosts);
  const [activeTag, setActiveTag] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  
  // 获取所有唯一的标签
  const allTags = ['all'];
  blogPosts.forEach(post => {
    post.tags.forEach(tag => {
      if (!allTags.includes(tag)) {
        allTags.push(tag);
      }
    });
  });
  
  // 根据标签和搜索词过滤博客文章
  useEffect(() => {
    let filtered = blogPosts;
    
    // 按标签过滤
    if (activeTag !== 'all') {
      filtered = filtered.filter(post => post.tags.includes(activeTag));
    }
    
    // 按搜索词过滤
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(post => 
        post.title.toLowerCase().includes(term) || 
        post.excerpt.toLowerCase().includes(term) ||
        post.content.toLowerCase().includes(term)
      );
    }
    
    setPosts(filtered);
  }, [activeTag, searchTerm]);

  // 处理搜索输入
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
  };

  // 处理标签点击
  const handleTagClick = (tag) => {
    setActiveTag(tag);
  };

  // 格式化日期
  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('zh-CN', options);
  };

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1
      }
    }
  };

  const itemVariants = {
    hidden: { y: 20, opacity: 0 },
    visible: {
      y: 0,
      opacity: 1,
      transition: {
        duration: 0.5
      }
    }
  };

  return (
    <div className="blog-page">
      <Breadcrumb />
      
      <div className="container">
        <div className="blog-header">
          <h1 className="page-title">我的博客</h1>
          <p className="page-description">
            分享我对技术、设计和行业趋势的见解与经验
          </p>
        </div>
        
        <div className="blog-filters">
          <div className="search-bar">
            <input
              type="text"
              placeholder="搜索文章..."
              value={searchTerm}
              onChange={handleSearchChange}
              className="search-input"
            />
          </div>
          
          <div className="tags-filter">
            {allTags.map((tag, index) => (
              <button
                key={index}
                className={`tag-btn ${activeTag === tag ? 'active' : ''}`}
                onClick={() => handleTagClick(tag)}
              >
                {tag === 'all' ? '全部' : tag}
              </button>
            ))}
          </div>
        </div>
        
        <AnimatePresence mode="wait">
          <motion.div 
            key={activeTag + searchTerm}
            className="blog-posts-grid"
            variants={containerVariants}
            initial="hidden"
            animate="visible"
            exit={{ opacity: 0 }}
          >
            {posts.length > 0 ? (
              posts.map(post => (
                <motion.div key={post.id} className="blog-card" variants={itemVariants}>
                  <div className="blog-image-container">
                    <img 
                      src={post.coverImage} 
                      alt={post.title} 
                      className="blog-image" 
                    />
                    <div className="blog-category">{post.category}</div>
                  </div>
                  <div className="blog-content">
                    <div className="blog-meta">
                      <span className="blog-date">{formatDate(post.date)}</span>
                    </div>
                    <h2 className="blog-title">
                      <Link to={`/blog/${post.id}`}>{post.title}</Link>
                    </h2>
                    <div className="blog-tags">
                      {post.tags.map((tag, i) => (
                        <span 
                          key={i} 
                          className="blog-tag"
                          onClick={() => handleTagClick(tag)}
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                    <p className="blog-excerpt">{post.excerpt}</p>
                    <Link to={`/blog/${post.id}`} className="read-more">
                      阅读全文
                    </Link>
                  </div>
                </motion.div>
              ))
            ) : (
              <div className="no-results">
                <h3>没有找到匹配的文章</h3>
                <p>尝试使用不同的搜索词或标签</p>
                <button 
                  className="btn btn-primary reset-btn"
                  onClick={() => {
                    setSearchTerm('');
                    setActiveTag('all');
                  }}
                >
                  重置过滤器
                </button>
              </div>
            )}
          </motion.div>
        </AnimatePresence>
      </div>
      
      <BackToTop />
    </div>
  );
};

export default BlogPage;
